package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.request.CallIn_outCUPApplicationReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.PPayCupUserService;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import net.sf.json.JSON;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 *
 * 银联支付确认接口
 * 外部系统 → 支付系统，数据：支付确认数据
 * Created by galen on 2018/11/22.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-205(银联)-外部支付确认<OutPayAgreeConfirmReqIn> 外部系统 → 支付系统，数据：支付确认数据")
public class CallIn_OutPayAgreeConfirmReqInController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @Autowired//支付申请
    private PPayService pPayService;

    @RequestMapping(value = "/payAgreeConfirmReq" , method = RequestMethod.POST)
    public String payAgreeConfirmReq(@RequestBody @Valid CallIn_outCUPApplicationReqIn requestJson, BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-205-外部支付确认<OutPayAgreeConfirmReqIn>请求JSON:" + requestJson.toString());
        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        System.out.println(requestJson.getThpinfo().toString());
        //根据用户号和协议编码获取注册信息
        PPayCUPUser payCUPUser = pPayCupUserService.findCUPUserByMeruseridAndAgreeid(requestJson.getMeruserid(),requestJson.getAgreeid());
        if(payCUPUser == null){
            retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "meruserid/agreeid");
            return retJson.toString();
        }
        PPay pay = pPayService.getByKey(requestJson.getPaymentId());
        if(pay == null){  //校验paymentId
            retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "paymentId");
            return retJson.toString();
        }
        //根据注册信息的商户id获取商户信息
        PPayCust payCust = getTLMessage(payCUPUser.getPayCustid(), FinalUtil.CUP_PAY_TYPE);
        String thpinfo = "";
        if(requestJson.getThpinfo() != null && requestJson.getThpinfo().toString() != "" && requestJson.getThpinfo().toString() != null){
            thpinfo = requestJson.getThpinfo().toString();
        }
        try {
            //请求通联callout
            logger.info("========协议编号："+payCUPUser.getPayAgreeid() +"=========商户号："+payCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.pay(MyDateUtil.NotString(requestJson.getPaymentId()),requestJson.getAgreeid(),requestJson.getSmscode(),thpinfo,payCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
                retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
                retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
                retJson.addBody("chnltrxid",map.get("chnltrxid"));
                retJson.addBody("trxid",map.get("trxid"));
                pay.setTrxid(map.get("trxid"));
                if (map.get("fintime") != null){
                    pay.setPayEndTime(String.valueOf(new SimpleDateFormat("yyyyMMddHHmmss").parse(map.get("fintime")).getTime()));
                }
                retJson.addBody(FinalUtil.THPINFO,map.get(FinalUtil.THPINFO));
                retJson.addBody("paymentId",requestJson.getPaymentId());
                if("0000".equals(map.get(FinalUtil.TRXSTATUS))){
                    pay.setPayStatus(FinalUtil.PAY_STATUS_SUSCSS);
                }else if(!"1999".equals(map.get(FinalUtil.TRXSTATUS))&&!"2000".equals(map.get(FinalUtil.TRXSTATUS))&&!"2008".equals(map.get(FinalUtil.TRXSTATUS))&&!"0000".equals(map.get(FinalUtil.TRXSTATUS))){
                    pay.setPayStatus(FinalUtil.PAY_STATUS_FAILUE);
                }
            }else {
                pay.setPayStatus(FinalUtil.PAY_STATUS_FAILUE);
                retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("通联异常参数：" + e.getMessage());
            retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
        }finally {
            pPayService.update(pay);
            return retJson.toString();
        }
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }

}
